<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\Token;
use app\http\TokenTrait;
use think\facade\Validate;
use think\Request;
use app\admin\service\Permissions;

class Login extends Common
{
    use TokenTrait;

    /**
     * 用户登录
     * @param Token $tokenModel
     * @return json 返回类型
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function login(Token $tokenModel)
    {
        $username = Request()->param('username', '');
        $password = Request()->param('password', '');
        if (empty($username) || empty($password)) {
            return $this->returnJson(422, '账号或密码不能为空');
        }
        $user = model('admin')->where(['username' => $username, 'password' => MD5($password)
        ])->find();
        if (empty($user)) {
            return $this->returnJson(422, '账号或密码输入错误');
        }
        $token = self::getToken($user['id']);
        $data['user'] = $user->hidden(['password']);
        $data['uid'] = $user['id'];
        $data['token'] = $this->setToken();
        $data['out_time'] = time() + 7 * 24 * 3600; // token有效期 7天
        $data['menu'] = (new Permissions())->getMenu($user['role_id']); // 目录
        if (empty($token)) {
            $result = self::createToken($data);
        } else {
            $result = self::updateToken($user['id'], $data);
        }
        if ($result) {
            $end = ['end_time' => time(), 'ip' => Request()->ip()];
            Admin::where('id', $user['id'])->update($end);
            return $this->returnJson(200, '登录成功', $data);
        } else {
            return $this->returnJson(500, '登录失败');
        }
    }

    /**
     * 用户注册
     *
     * @param Request $request
     * @param Admin $adminModel
     * @return json 返回类型
     */
    public function register(Request $request, Admin $adminModel)
    {
        $req = $request->only([
            'username',
            'password'
        ], 'post');
        $validate = Validate::make([
            'username' => 'require|unique:admin|/^1[34578]\d{9}$/',
            'password' => 'require'
        ]);
        // 'code' => 'require|eq:1234'
        if (! $validate->check($req)) {
            return json([
                'code' => 422,
                'msg' => $validate->getError()
            ], 422);
        }
        $req['level'] = 1;
        $result = $adminModel->saveData($req);
        if (! empty($result)) {
            return json([
                'code' => 200,
                'msg' => '注册成功'
            ]);
        } else {
            return json([
                'code' => 404,
                'msg' => '注册失败'
            ]);
        }
    }

    public function getCode(Request $request, Admin $adminModel)
    {
        return $this->returnJson(200, 'ok', 1234);
    }
}
